require 'sinatra/base'
require 'json'
require 'active_support'
require 'active_support/core_ext/hash'
require 'rest_base/authentication'

module RestBase
  class Application < Sinatra::Base
    attr_reader :request_body
    attr_reader :request_version
    attr_reader :errored
    attr_reader :forensics

    configure do
      disable :raise_errors
      disable :show_exceptions
      set :api_version, 1
      set :authentication, RestBase::Authentication::BasicAuthentication.new([])
      disable :header_versioning
    end

    set(:version) do |value|
      condition do
        has_version?("version=#{value}")
      end
    end
    
    set(:method) do |method|
      condition do
        request.request_method.downcase.to_sym == method.to_s.downcase.to_sym
      end
    end

    before do
      status 200

      set_api_version if settings.header_versioning
      set_request_body
      setup_forensics
      error 401 unless authenticated?
    end

    after do
      response.body = nil if response.body.is_a?(Array) && response.body.length == 1 && response.body[0].empty?     
      response.body = create_response()
      response.headers['Content-Type'] += ";version=#{@request_version}"
    end
  end
end